package com.project.les;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
  
public class TwitterPost {
  
	private final String consumerKey = "wTFUMHQBfJ1h4jm0RocQGw";
	private final String consumerSecret = "1vPm5CxX37GD2pFaQU34P81XpZ1VNHFqOKwdsoY4jI";
	private final String CALLBACKURL = "feriados-android:///";

	private Twitter twitter;
	private static TwitterPost __instance;
	private Activity callerActivity;
	private Integer lastPostId = -1;
	private String lastMessageToPost = null;
	
	
	public Integer getAndClearLastPostId() {
		Integer result = this.lastPostId;
		this.lastPostId = -1;
		return result;
	}
	
	public void setLastPostId(Integer lastPostId) {
		this.lastPostId = lastPostId;
	}
	
	private TwitterPost() {
		twitter = new TwitterFactory().getInstance();
		twitter.setOAuthConsumer(consumerKey, consumerSecret);
	}
	
	public void setCallerActivity(Activity activity) {
		this.callerActivity = activity;
	}
	
	public Activity getCallerActivity() throws Exception {
		if (this.callerActivity == null)
			throw new Exception("Activity não definida");
		
		return this.callerActivity;
	}
	
	public static TwitterPost getInstance() {
		if (TwitterPost.__instance == null)
			TwitterPost.__instance = new TwitterPost();
		
		return TwitterPost.__instance;
	}
	
	public void login() {
		try {
			AccessToken accessToken = loadAccessToken();
			if (accessToken == null) {
				twitter = new TwitterFactory().getInstance();
				twitter.setOAuthConsumer(consumerKey, consumerSecret);
				
				RequestToken requestToken =	twitter.getOAuthRequestToken(CALLBACKURL);
				
				Log.w("WARNING", "requestToken");
				String url = requestToken.getAuthenticationURL();
				Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
				it.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				this.getCallerActivity().startActivity(it);
				
				saveRequestData(requestToken.getToken(), requestToken.getTokenSecret());
			} else {
				twitter.setOAuthAccessToken(accessToken);
			}
		} catch (TwitterException e) {
			Log.e("ERROR", e.getMessage());
			//e.printStackTrace();
			//showToast(e.getMessage());
			showToast("Não foi possível conectar com o Twitter. Verifique sua conexão com a internet.");
		} catch (Exception e) {
			Log.e("ERROR", e.getMessage());
			//e.printStackTrace();
			//showToast(e.getMessage());
			showToast("Não foi possível conectar com o Twitter. Verifique sua conexão com a internet.");
		}
		
	}
	
	
	protected void onActivityResume(String oauthVerifier) {
		
		try {
			//Uri uri = this.getCallerActivity().getIntent().getData();
			
			//if (uri != null) {
				
			if (oauthVerifier != null) {
				
				//String oauthVerifier = uri.getQueryParameter("oauth_verifier");
				
				try {
					RequestToken requestToken = loadRequestToken();
					AccessToken at = twitter.getOAuthAccessToken(requestToken, oauthVerifier);
			
					saveAccessToken(at.getToken(), at.getTokenSecret());
					
					//twitter.updateStatus(this.lastMessageToPost);
					//this.showToast("Feriado twittado com sucesso!");
					
					this.tweetMessage(this.lastMessageToPost);
					this.lastMessageToPost = null;
					
				} catch (TwitterException e) {
					e.printStackTrace();
					//showToast(e.getMessage());
					showToast("Ocorreu um erro ao acessar o twitter. Verifique sua conexão com a internet.");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			showToast("Ocorreu um erro ao acessar o twitter. Verifique sua conexão com a internet.");
			//howToast(e.getMessage());
		}
	}
	
	
	public Boolean tweetMessage(String message) {
		try {
			if (this.loadAccessToken() != null) {
				
				twitter.updateStatus(message);
				this.showToast("Feriado twittado com sucesso!");
				Log.w("WARNING", "Feriado twittado com sucesso!");
				return true;
			} else {
				this.lastMessageToPost = message;
				this.showToast("Faça o login antes de Twittar");
				return false;
			}
		} catch (Exception e) {
			e.printStackTrace();
			//showToast(e.getMessage());
			this.showToast("Ocorreu um erro ao acessar o Twitter, tente mais tarde.");
		}
		
		return false;
	}
	
	private void showToast(String s) {
		try {
			Toast.makeText(this.getCallerActivity(), s, Toast.LENGTH_LONG).show();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private RequestToken loadRequestToken() throws Exception {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getCallerActivity());
		String reqToken = prefs.getString("request_token", null);
		String reqTokenSecret =	prefs.getString("request_tokensecret", null);
			
		return new RequestToken(reqToken, reqTokenSecret);
	}
		 
	private void saveRequestData(String requestToken, String requestTokenSecret) throws Exception{
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getCallerActivity());
		SharedPreferences.Editor editor = prefs.edit();
		
		editor.putString("request_token", requestToken);
		editor.putString("request_tokensecret", requestTokenSecret);
		
		editor.commit();
	}
		 
	private AccessToken loadAccessToken() throws Exception {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getCallerActivity());
		String acToken = prefs.getString("access_token", null);
		String acTokenSecret = prefs.getString("access_tokensecret", null);
		
		if (acToken != null || acTokenSecret != null) {
			return new AccessToken(acToken, acTokenSecret);
		}
		return null;
	}
		 
	private void saveAccessToken(String accessToken, String accessTokenSecret) throws Exception {
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this.getCallerActivity());
		SharedPreferences.Editor editor = prefs.edit();
		
		editor.putString("access_token", accessToken);
		editor.putString("access_tokensecret", accessTokenSecret);
		
		editor.commit();
	}
	
	public void clickLogout(View v) throws Exception {
		this.saveAccessToken(null, null);
	}
	
}